<template>
  <div>
    <el-upload
      :action="iconUrl"
      class="avatar-uploader"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :with-credentials="true"
      accept=".jpg,.jpeg,.png"
    >
      <img
        v-if="imageUrl"
        :src="imageUrl"
        class="avatar"
      />
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
      ></i>
    </el-upload>
  </div>
</template>

<script>
import { getUser } from "../../../api/common-api/personInformation";

export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          token: "",
        };
      },
    },
  },
  data() {
    return {
      head: "",
      iconUrl: "",
      imageUrl: '',
    };
  },
  created() {
    getUser().then((res) => {
      this.head = res.data[0]['head'];
    });
    this.iconUrl = process.env.VUE_APP_FILE_API + `/users/upicon?token=` + this.user.token;
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.$message.success("头像修改成功,待下次登陆更换显示", "success");
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      this.imageUrl = process.env.VUE_APP_FILE_API + "/file/" + this.head
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG、PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  margin: auto;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
